package com.socketeg.demo.socket;

import com.socketeg.demo.myThread.ServerThread;
import com.socketeg.demo.socket.ManagerClient;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

import static javax.swing.UIManager.put;

/**
 * 服务端
 */
@Component
public class Server {

    public void startServer() throws IOException {
        ServerSocket server = new ServerSocket(8500);

        // 循环等待客户端连入
        while (true) {
            //得到客户端 （阻塞操作）
            Socket client = server.accept();
            //使用异步线程进行cs通讯
            ServerThread serverThread = new ServerThread(client);
            serverThread.start();
        }
    }

    public String pushMessageToClient(String addr, String message) throws IOException {
        Socket socket = ManagerClient.getClient(addr);
        if (socket == null) {
            return "不存在的客户端";
        }
        OutputStream outputStream = socket.getOutputStream();
        PrintStream printStream = new PrintStream(outputStream);
        printStream.println(message);
        return "成功";
    }
}
